import 'whatwg-fetch'

const baseUrl = 'http://localhost:801/api'

const get = (url, query) => {
  var _url = baseUrl + url
  if (query) {
    _url += '?' + query
  }
  var token = localStorage.token
  return fetch(_url, {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + token
    }
  }).then((response) => {
    if (response.status === 200) {
      return response.json()
    } else {
      return response.json()
    }
    // return Promise.reject(new Error(response.status_code))
  }).catch((error) => {
    console.log(error)
  })
}

const post = (url, params) => {
  var _url = baseUrl + url
  var token = localStorage.token
  console.log(JSON.stringify(params))
  return fetch(_url, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + token
    },
    body: JSON.stringify(params)
  }).then((response) => {
    if (response.status === 200) {
      return response.json()
    } else {
      return response.json()
    }
    // return Promise.reject(new Error(response.status_code))
  }).catch((error) => {
    console.log(error)
  })
}

/* 用户登录 */
export const fetchLogin = (params) => {
  var url = '/login'
  return post(url, params).then((json) => {
    if (json.token !== undefined) {
      return json.token
    } else {
      return null
    }
  })
}
/* 获取首页数据 */
export const fetchIndexList = () => {
  var url = '/list'
  return get(url).then((json) => {
    if (json.data !== undefined) {
      return json.data
    } else {
      return null
    }
  })
}
/* 获取歌单详情 */
export const fetchPlaylistDetail = (id) => {
  var url = '/playlist/' + id
  return get(url).then((json) => {
    if (json.code === 200) {
      return json.data
    } else {
      return null
    }
  })
}
/* 获取评论列表 */
export const fetchCommentList = (fromType, fromId, page) => {
  var url = '/comment'
  var query = 'from_type=' + fromType + '&from_id=' + fromId + '&page=' + page
  return get(url, query).then((json) => {
    if (json.data !== undefined) {
      return json
    } else {
      return null
    }
  })
}
/* 添加评论 */
export const fetchCommentStore = (params) => {
  var url = '/comment/store'
  return post(url, params).then((json) => {
    return json
  })
}
